package com.suray.wcs.web.system.controller;

import com.suray.commin.annotation.Log;
import com.suray.commin.core.controller.BaseController;
import com.suray.commin.core.controller.ResponseData;
import com.suray.commin.core.page.TableDataInfo;
import com.suray.commin.core.utils.*;
import com.suray.commin.enmus.BusinessType;
import com.suray.commin.core.utils.SecurityUtils;
import com.suray.commin.core.pojo.LoginUser;
import com.suray.commin.core.entity.RoleDB;
import com.suray.wcs.service.system.service.IRoleDBService;
import com.suray.wcs.service.system.service.IUserDBService;
import com.suray.wcs.service.system.service.impl.SysPermissionService;
import com.suray.wcs.service.system.service.impl.TokenService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 角色信息
 *
 * @author shaozn
 */
@RestController
@RequestMapping(value = "/role")
public class RoleDBController extends BaseController {
    @Autowired
    private IRoleDBService IRoleDBService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private IUserDBService IUserDBService;

    @ApiOperation("查询角色列表")
    @PreAuthorize("@ss.hasPermi('role:list')")
    @GetMapping("/list")
    public TableDataInfo list(RoleDB role) {
        startPage();
        List<RoleDB> list = IRoleDBService.selectRoleList(role);
        return getDataTable(list);
    }

    /**
     * 根据角色编号获取详细信息
     */
    @ApiOperation("根据角色编号获取详细信息")
    @GetMapping(value = "/{roleId}")
    public ResponseData getInfo(@PathVariable Long roleId) {
        return ResponseData.success(IRoleDBService.selectRoleById(roleId));
    }

    /**
     * 新增角色
     */
    @ApiOperation("新增角色")
    @PreAuthorize("@ss.hasPermi('role:add')")
    @Log(title = "角色管理", method = "新增角色", businessType = BusinessType.INSERT)
    @PostMapping
    public ResponseData add(@Validated @RequestBody RoleDB role) {
        if (UserConstants.NOT_UNIQUE.equals(IRoleDBService.checkRoleNameUnique(role))) {
            return ResponseData.error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(IRoleDBService.checkRoleKeyUnique(role))) {
            return ResponseData.error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setCreateBy(SecurityUtils.getUsername());
        return toAjax(IRoleDBService.insertRole(role));

    }

    /**
     * 响应返回结果
     *
     * @param rows 影响行数
     * @return 操作结果
     */
    protected ResponseData toAjax(int rows) {
        return rows > 0 ? ResponseData.success() : ResponseData.error();
    }

    /**
     * 修改保存角色
     */
    @ApiOperation("修改保存角色")
    @PreAuthorize("@ss.hasPermi('role:edit')")
    @Log(title = "角色管理", method = "修改保存角色", businessType = BusinessType.UPDATE)
    @PutMapping
    public ResponseData edit(@Validated @RequestBody RoleDB role) {
        IRoleDBService.checkRoleAllowed(role);
        if (UserConstants.NOT_UNIQUE.equals(IRoleDBService.checkRoleNameUnique(role))) {
            return ResponseData.error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(IRoleDBService.checkRoleKeyUnique(role))) {
            return ResponseData.error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateBy(SecurityUtils.getUsername());

        if (IRoleDBService.updateRole(role) > 0) {
            // 更新缓存用户权限
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin()) {
                loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser()));
                loginUser.setUser(IUserDBService.selectUserByUserName(loginUser.getUser().getUserName()));
                tokenService.setLoginUser(loginUser);
            }
            return ResponseData.success();
        }
        return ResponseData.error("修改角色'" + role.getRoleName() + "'失败，请联系管理员");
    }

    /**
     * 修改保存数据权限
     */
    @ApiOperation("修改保存数据权限")
    @PreAuthorize("@ss.hasPermi('role:edit')")
    @Log(title = "角色管理", method = "修改保存数据权限", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public ResponseData dataScope(@RequestBody RoleDB role) {
        IRoleDBService.checkRoleAllowed(role);
        return toAjax(IRoleDBService.authDataScope(role));
    }

    /**
     * 状态修改
     */
    @ApiOperation("状态修改")
    @PreAuthorize("@ss.hasPermi('role:edit')")
    @Log(title = "角色管理", method = "状态修改", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public ResponseData changeStatus(@RequestBody RoleDB role) {
        IRoleDBService.checkRoleAllowed(role);
        role.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(IRoleDBService.updateRoleStatus(role));
    }

    /**
     * 删除角色
     */
    @ApiOperation("删除角色")
    @PreAuthorize("@ss.hasPermi('role:remove')")
    @Log(title = "角色管理", method = "删除角色", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    public ResponseData remove(@PathVariable Long[] roleIds) {
        return toAjax(IRoleDBService.deleteRoleByIds(roleIds));
    }

    /**
     * 获取角色选择框列表
     */
    @ApiOperation("获取角色选择框列表")
    @GetMapping("/optionselect")
    public ResponseData optionselect() {
        return ResponseData.success(IRoleDBService.selectRoleAll());
    }

    @ApiOperation("导出角色")
    @Log(title = "角色管理", method = "导出角色", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('role:export')")
    @GetMapping("/export")
    public ResponseData export(RoleDB role) {
        List<RoleDB> list = IRoleDBService.selectRoleList(role);
        ExcelUtil<RoleDB> util = new ExcelUtil<RoleDB>(RoleDB.class);
        return util.exportExcel(list, "角色数据");
    }
}

